package com.wang.bootbuilder.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wang.bootbuilder.entity.param.LoginParam;
import com.wang.bootbuilder.entity.pojo.Role;
import com.wang.bootbuilder.entity.pojo.SessionUser;
import com.wang.bootbuilder.entity.pojo.User;
import com.wang.bootbuilder.execption.CaptchaException;
import com.wang.bootbuilder.mapper.RoleMapper;
import com.wang.bootbuilder.mapper.UserMapper;
import com.wang.bootbuilder.security.CaptchaFilter;
import com.wang.bootbuilder.tools.JsonResult;
import com.wang.bootbuilder.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

@Service
public class LoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    CaptchaFilter captchaFilter;

    public JsonResult login(LoginParam param) {

        // 验证码验证
        try {
            captchaFilter.doFilterInternal(param.getKey(), param.getVerification());
        } catch (CaptchaException e) {
            return JsonResult.error().message(e.getMsg());
        }

        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("username", param.getUsername()).eq("password", param.getPassword());
        User user = userMapper.selectOne(wrapper);
        if (ObjectUtils.isNull(user)) {
            return JsonResult.error().message("用户名或密码不正确!");
        }
        // 根据登录的用户获取权限信息
        Role role = roleMapper.selectById(user.getRoleId());
        String menuIds = role.getMenuIds();
        // 登录用户存在的话就把该用户存入session
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        session.setAttribute("userinfo", new SessionUser(user.getId(), user.getUsername(), menuIds));
        return JsonResult.ok().data("user", user);

    }

}
